%\documentclass[12pt, titlepage, a4paper]{report}
% For printed document - always starts a new chapter on the right-side page (leaves blank pages):
%\documentclass[12pt, titlepage, a4paper, openright, twoside]{report}
\documentclass[12pt, titlepage, a4paper]{report}
% twoside
%% Needed packages:
\usepackage{pdfpages}       % used for introducing the title PDF page
%\usepackage{a4wide}        % spreads text over the whole width of the page

%\renewcommand{\familydefault}{\sfdefault}
%\usepackage{helvet}

\usepackage[utf8x]{inputenc}    % encoding
\usepackage[english]{babel} % multilingual typesetting
\usepackage{graphicx}       % adds graphics
\usepackage[pdftex]{hyperref}   % hyper-refs inside the doc
\usepackage{url}        % formats urls
\usepackage{cite}       % citations from bibtex
\usepackage{makeidx}        % index
\usepackage{robustindex}    % index

%% Add/remove packages here:
\usepackage{ucs}
\usepackage{parskip}
\usepackage{wrapfig}
\usepackage{array} 
\usepackage{rotating}
\usepackage{alltt}
\usepackage{latexsym}
\usepackage{amsmath, amsthm, amssymb}
\usepackage{setspace}
%\usepackage[hide]{ed}
\usepackage{color}
\usepackage{listings}
\lstset{float=htb,columns=fullflexible,frame=lines,basicstyle=\scriptsize, language=XML,
        numbers=left,stepnumber=5,numberstyle=\tiny,showstringspaces=false}

\pagestyle{headings}
\makeindex    % obligatory with robustindex

\newenvironment{mylisting}
{\begin{list}{}{\setlength{\leftmargin}{1em}}\item\footnotesize}
{\end{list}}

\newenvironment{mytinylisting}
{\begin{list}{}{\setlength{\leftmargin}{1em}}\item\tiny\bfseries}
{\end{list}}

\setlength{\textwidth}{14.66cm} % height of main text
\setlength{\textheight}{22.2cm}    % width of text

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Document
\begin{document}
\sloppy%: Title -----------------------------------------------
\thispagestyle{empty} {\vspace*{-2.8cm}
 \hspace*{7.5cm} \includegraphics[clip,width=75mm,viewport=0 0 235 85]{JU_LOGO_4C}}
\vspace{3.5cm}
% Title


\begin{center}\begin{LARGE}Implementation and Evaluation of the \\Simple Network Management Protocol over IEEE 802.15.4 Radios under the Contiki Operating System\end{LARGE}\end{center}

\noindent \begin{center}
{by{\LARGE } }
\par\end{center}{\LARGE \par}

\noindent \begin{center}
\textbf{Siarhei Kuryla}
\par\end{center}

\noindent \begin{center}
{A thesis for the conferral of a Master of Science in Smart Systems{\LARGE } }
\par
\end{center}{\LARGE \par}

\vspace{20 mm}

\begin{tabular}{ r l }
  Superviser: & Prof. Dr. J\"urgen Sch\"onw\"alder\\
  Second Reader:  & ????\\
\end{tabular}

\textbf{\LARGE \vfill{}
}{\LARGE \par}

\noindent {\normalsize
Date of Submission: \\%August 23$^{rd}$, 2010}\\
{\LARGE{} {\hspace*{-0.17cm} \rule[3mm]{\textwidth}{0.75pt}}
}\\


\normalsize
\noindent \textit{School of Engineering and Science}\\
\textit{Jacobs University Bremen gGmbH}\\
\textit{Campus Ring 1}\\
\textit{28759 Bremen}\\
\textit{Germany}\\
\textit{ }\\
\newpage{}

\section*{\thispagestyle{empty}Declaration}
\thispagestyle{empty}
This thesis is the result of my own independent work and has not previously been accepted in substance for any degree and is not concurrently submitted in candidature for any degree. 

This thesis is being submitted in fulfillment of the requirements
for the degree of Master of Science in Smart Systems.

\textbf{\LARGE \vspace{1in}
}{\LARGE \par}

\begin{flushright}
.......................................................
\par\end{flushright}

\begin{flushright}
Siarhei Kuryla
\par\end{flushright}


\newpage{}
\section*{\thispagestyle{empty}Acknowledgments}
I would like to first of all thank my supervisor, Prof. Dr. J\"urgen Sch\"onw\"alder,                                           for his continuous guidance throughout this thesis and for many helpful comments.

I also extend a warm thank you to Tatsiana Zhytsinets, my family and friends, who put up with my busy schedule over several months.

Thank you!


\section*{\newpage{}\thispagestyle{empty}\pdfbookmark{Abstract}{Abstract}Abstract}
Low-power wireless personal area networks (LoWPANs), composed of a large number of tiny devices with wireless communication capabilities, are becoming increasingly important due to their reduced cost and a range of real world applications. Devices in such networks are expected to be deployed in exceedingly large numbers. Furthermore, they are expected to have limited display and input capabilities. This makes network management functionality critical for LoWPANs. The Simple Network Management Protocol (SNMP) is a widely deployed application protocol for network management and data retrieval. In the course of this thesis, an SNMP agent for devices supporting IEEE 802.15.4 Radios and the Contiki Embedded Operating System has been developed. The evaluation of the implementation has been performed on the AVR Raven board hardware platform.

\newpage
\tableofcontents
%%\listoffigures
\newpage

\setcounter{page}{1} \pagenumbering{arabic}
%%
%   Introduction
%%
\chapter{Introduction}
A low-power wireless personal area network (LoWPAN) is a simple low cost communication network that allows wireless connectivity in applications with limited power and relaxed throughput requirements. LoWPANs conform to the IEEE 802.15.4 standard \cite{ieee802.15.4} and typically include devices limited in their computational power, memory, and energy availability. Such networks can benefit from IP and, in particular, IPv6 networking. IP-based devices can be easily connected to other IP-based networks by reusing existing infrastructure. However, due to the limited nature of IEEE 802.15.4 devices the IPv6 protocol \cite{rfc2460} needs to be adapted for its use in LoWPANs.  Devices within LoWPANs are expected to be deployed in exceedingly large numbers. Furthermore, they are expected to have limited display and input capabilities. This makes network management functionality critical for LoWPANs. The Simple Network Management Protocol (SNMP) is a widely deployed application layer protocol for network management and data retrieval. SNMP is datagram-oriented and the implementations of SNMP can be very lightweight.  It may fit LoWPAN applications very well. The purpose of this thesis is to investigate whether the SNMP functionality may be reused "as is" in LoWPANs.

The rest of the thesis is organized as follows. Chapter \ref{ch:ieee802.15.4} provides an introduction to the IEEE 802.15.4 standard. Chapter \ref{ch:6lowpan} describes the adaptation layer that allows the transmission of IPv6 packets over 802.15.4 links. Chapter \ref{ch:snmp} gives an overview of the Simple Network Management Protocol. A short overview of the current approaches on network management in 6LoWPANs is given in Chapter \ref{ch:relatedwork}. Chapter \ref{ch:hardware} provides an introduction to the hardware platform and the Contiki Operating System.  Chapter \ref{ch:snmpv1-impl} describes the implementation details, including its main features and the overall architecture. Chapter \ref{ch:eval} presents performance results and resource consumption statistics for the implemented SNMP agent. Finally, the thesis is concluded in Chapter \ref{ch:conclusions}.

%%%
%	IEEE 802.15.4
%%%
\chapter{IEEE 802.15.4}\label{ch:ieee802.15.4}
The IEEE 802.15.4 standard developed by the 802.15.4 Task Group within the IEEE specifies the physical layer and media access control for low-rate wireless personal area networks providing node-to-node frame delivery between devices within reachable distance from each other. The standard is targeted at low cost, low speed and low power consumption devices. Several versions of the standard have been published, such as 802.15.4-2003 \cite{ieee802.15.4}, 802.15.4-2006 \cite{ieee802.15.4-2006}, 802.15.4a-2007 \cite{ieee802.15.4a-2007}, 802.15.4c-2009 \cite{ieee802.15.4c-2009} and 802.15.4d-2009 \cite{ieee802.15.4d-2009} . This chapter provides an overview of the IEEE 802.15.4 standard.

\section{Device Types}
The IEEE 802.15.4 standard distinguishes between two types of nodes, reduced-function devices (RFDs) and full-function devices (FFDs). FFDs typically have more resources, implement the complete protocol set and may be mains powered. An FFD can talk to RFDs or other FFDs, while an RFD can talk only to an FFD. FFDs aid RFDs by providing functions such as network coordination and packet forwarding. An RFD is intended for applications that are extremely simple, which do not have the need to send large amounts of data and may only associate with a single FFD at a time. Therefore, RFDs implement a minimal subset of the IEEE 802.15.4 protocol and can be implemented using minimal resources and memory capacity.

Two or more devices within a personal operating space communicating on the same physical channel constitute a wireless personal area network (WPAN). However, a network has to include at least one FFD.

\section{Network Topologies}
An 802.15.4 network may operate in either the star or the peer-to-peer topology. In the star topology devices communicate with a single central personal area network (PAN) coordinator. Only an FDD device can be a PAN coordinator. The PAN coordinator is usually mains powered, while the other devices are most likely battery operated. In the peer-to-peer topology a device can communicate with any other device as long as they are in range of each other. Based on the peer-to-peer topology more complex network formations may be constructed, such as mesh networking topology. However, the standard does not define a network layer, therefore, routing is not directly supported, but such an additional layer can add support for multihop communication. All devices operating on a network of either topology have unique 64 bit extended addresses. This address can be used for direct communication within the PAN. Each independent PAN selects a unique identifier. This PAN identifier allows communication between
devices within a network using short 16 bit addresses and enables transmissions between devices across independent networks.

\section{Frame Structure}
The basic unit of data transport is a frame. The standard defines four frame structures: a beacon frame, used by a coordinator to transmit beacons; a data frame, used for all transfers of data;  an acknowledgement frame, used for confirming successful frame reception; a MAC command frame, used for handling all MAC control transfers. Additionally, a superframe structure may be defined by the coordinator. In such case two beacons act as superframe limits and provide synchronization to other devices. A superframe consists of sixteen equal-length slots, which can be further divided into an active part and an inactive part, during which the coordinator may enter power saving mode. Any device wishing to communicate during the contention access period (CAP) between two beacons shall compete with other devices using a slotted CSMA-CA mechanism. For applications requiring specific data bandwidth, the PAN coordinator may dedicate portions of the active superframe, which form the contention-free period (CFP).

An important aspect of 802.15.4 is its limitation on the frame size, which is specified by the frame length 7 bit field (0-127 bytes). Taking into account the frame header, which is up to 25 octets (disabled security), this leaves 102 bytes for the payload of the higher layers.

\section{Security}
The standard defines several security services such as maintaining an access control list (ACL) and
using symmetric-key cryptography to protect transmitted frames. Access control is a security service that provides the ability for a device to select the other devices with which it is willing to communicate. If the access control service is enabled, a device maintains a list of devices in its ACL from which it expects to receive frames.                        In order to protect data from being read by parties without permission, data may be encrypted using a key shared by a group of devices or using a key shared between two peers. However, key management is not specified in the standard and must be provided by the higher layers. Security services also specify frame integrity that uses a message integrity code to protect data from being modified by parties without the cryptographic key. This provides assurance that data came from a party with the cryptographic key. 


%%
%   6LoWPAN
%%

\chapter{IPv6 over IEEE 802.15.4}\label{ch:6lowpan}
%The Internet Protocol (IP) is the most widely deployed network layer protocol. Internet Protocol Version 4 (IPv4) is still the dominant protocol of the Internet, although the successor, Internet Protocol Version 6 (IPv6) \cite{rfc2460} is being deployed actively worldwide. The application of IP technologies to LoWPANs would provide a number of benefits. IP-based technologies are well-known and proven which allows to use the existing infrastructure. IP-based devices can be easily connected to other IP-based networks. Today there exist a lot of ready-to-use tools for diagnostics and management of IP networks.

The 6lowpan (Internet Protocol Version 6 over Low power Wireless Personal Area Networks) working group of the IETF is concerned with the specification of mechanisms to allow IPv6 packet transmission over IEEE 802.15.4 based networks. The working group has already completed two documents: "IPv6 over Low-Power Wireless Personal Area Networks (6LoWPANs): Overview, Assumptions, Problem Statement, and Goals" \cite{rfc4919} that documents and discusses the problem statement and "Transmission of IPv6 Packets over IEEE 802.15.4 Networks" \cite{rfc4944} that defines the format for the adaptation between IPv6 and 802.15.4. The latter document describes the frame format for transmission of IPv6 packets and the method of forming IPv6 link-local addresses and statelessly autoconfigured addresses on IEEE 802.15.4 networks.

%As described in Chapter \ref{ch:ieee802.15.4}, IEEE 802.15.4 defines four types of frames: beacon frames, MAC command frames, acknowledgement frames, and data frames.  IPv6 packets are carried on data frames.  Data frames may optionally request acknowledgments to aid link-layer recovery.

This chapter describes the Adaptation Layer and Header Compression Formats that have been introduced to allow the transmission of IPv6 packets over 802.15.4 links.

\section{Addressing}
IEEE 802.15.4 defines addresses of two types: IEEE 64-bit extended addresses or 16-bit short addresses unique within the PAN. Both types are supported by 6LoWPAN. 6LoWPAN supports stateless address autoconfiguration, which allows to obtain the interface identifier \cite{rfc4291} for an IEEE 802.15.4 interface  based on the EUI-64 identifier \cite{eui64} \cite{rfc2464} assigned to the IEEE 802.15.4 device. Even though all 802.15.4 devices have an EUI-64 address, 16-bit short addresses also can be used for address autoconfiguration.  In this case, a pseudo 48-bit address is formed by concatenating 16 zero bits to the 16-bit PAN ID, the resulting 32 bits are concatenated with the 16-bit short address. The interface identifier is formed from this 48-bit address as defined in the "IPv6 over Ethernet" specification \cite{rfc2464}. The IPv6 link-local address for an IEEE 802.15.4 interface is formed by appending the interface identifier to the prefix \texttt{FE80::/64}.

\section{Adaptation Layer}\label{sec:adapt.layer}
The IPv6 minimum Maximum Transmission Unit (MTU) size is defined as 1280 octets. As described in Chapter \ref{ch:ieee802.15.4}, the maximum IEEE 802.15.4 frame size is limited to 127 octets.  Taking into account the maximum frame overhead of 25 octets (disabled security), 102 octets are left at the media access control layer. Link-layer security imposes further overhead, which in the maximum case (21 octets for AES-CCM-128) leaves only 81 octets available, which is far below the minimum IPv6 packet size. Therefore, a fragmentation and reassembly adaptation layer is provided at the layer below IP.

Even though 802.15.4 networks are expected to commonly use mesh routing, the IEEE 802.15.4-2003 \cite{ieee802.15.4} specification does not define such capability. In order to support mesh routing, in addition to the hop-by-hop source and destination link-layer addresses, the originator and final destination addresses need to be known. For this purpose a Mesh Addressing header is introduced.

IPv6 datagrams transported over IEEE 802.15.4 are prefixed by an encapsulation header stack. Each header in the header stack contains a header type followed by zero or more header fields.  There are four encapsulation headers defined: Mesh Addressing Header, Broadcast Header, Fragmentation Header and Dispatch Header. The first three of them are optional, whereas the last one is required.

\subsection{Dispatch Header}\label{subsec:dispatch}
The dispatch header is shown in Figure \ref{fig:dispatch.header}. The dispatch type is defined by a zero bit as the first bit followed by a one bit. 

\begin{figure}[htp]
\centering
\begin{mylisting}
\begin{verbatim}
                     1                   2                   3
   0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  |0 1| Dispatch  |  type-specific header
  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
\end{verbatim}
\end{mylisting}
\caption{Dispatch Type and Header}\label{fig:dispatch.header}
\end{figure}
The dispatch value identifies the type of payload immediately following the Dispatch Header. This can be, for example, a compressed or uncompressed IPv6 header. More details can be found in \cite{rfc4944}.

\subsection{Mesh Addressing Header}\label{subsec:mesh.header}

The mesh header type is defined by a one bit as the first bit followed by a zero bit:
\begin{figure}[htp]
\centering
\begin{mylisting}
\begin{verbatim}
                       1                   2                   3
   0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  |1 0|V|F|HopsLft| originator address, final address
  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
\end{verbatim}
\end{mylisting}
\caption{Mesh Addressing Type and Header}\label{fig:mesh.header}
\end{figure}

The \texttt{V} and \texttt{F} bits indicate whether an extended 64-bit (EUI-64) or short 16-bit address is used for the originator and the final destination respectively. The \texttt{HopsLft} field is a hop limit which is decremented by every forwarding node. The rest of the header specifies the originator and final destination link-layer addresses.

\subsection{Fragmentation Header}\label{subsec:frag.header}
When an entire IPv6 datagram may not fit within a single 802.15.4 frame, it is broken into several fragments. The first link fragment contains the fragment header shown in Figure \ref{fig:first.fragment}.
\begin{figure}[htp]
\centering
\begin{mylisting}
\begin{verbatim}
                      1                   2                   3
  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  |1 1 0 0 0|    datagram_size    |         datagram_tag          |
  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
\end{verbatim}
\end{mylisting}
\caption{First Fragment}\label{fig:first.fragment}
\end{figure}

The second and subsequent link fragments contains a fragmentation header that conforms to the format shown in Figure \ref{fig:sub.fragment}.

\begin{figure}[htp]
\centering
\begin{mylisting}
\begin{verbatim}
                     1                   2                   3
   1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  |1 1 1 0 0|    datagram_size    |         datagram_tag          |
  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  |datagram_offset|
  +-+-+-+-+-+-+-+-+
\end{verbatim}
\end{mylisting}
\caption{Subsequent Fragments}\label{fig:sub.fragment}
\end{figure}

The first and subsequent fragment header types are identified by the binary sequences \texttt{11000} and \texttt{11100} respectively.  The  \texttt{datagram\_size} 11-bit field encodes the size of the entire IP packet before link-layer fragmentation.  The \texttt{datagram\_tag} field is the same for all link fragments of a datagram and incremented by the sender for successive fragmented datagrams. The \texttt{datagram\_offset} field is present only in the second and subsequent link fragments and specifies the offset of the fragment from the beginning of the payload datagram.

\subsection{Broadcast Header}\label{subsec:broad.header}
Broadcast is an additional mesh routing functionality. For that a broadcast header is defined, the format of which is shown in Figure \ref{fig:broad.header}.
\begin{figure}[htp]
\begin{mylisting}
\begin{verbatim}
                                       1
                   0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
                  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
                  |0|1|0|1|0|0|0|0|Sequence Number|
                  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
\end{verbatim}
\end{mylisting}
\caption{Broadcast Header
}\label{fig:broad.header}
\end{figure}

The broadcast header consists of the dispatch type \texttt{01010000} followed by a sequence number field used to detect duplicate packets. This field is incremented by the originator whenever it sends a new mesh broadcast or multicast packet.

\section{Header Compression}\label{sec:hc}
As described in Section \ref{sec:adapt.layer}, 81 octets are left in an IEEE 802.15.4 frame for IPv6. The IPv6 header is 40 octets long which leaves only 41 octets for upper-layer protocols, like UDP.  The latter uses 8 octets in the header, which leaves 33 octets for application data.
The fragmentation and reassembly layer, described in Section \ref{sec:adapt.layer}, will also use at least one additional octet. This makes header compression almost unavoidable.

RFC 4944 \cite{rfc4944} defines a stateless header compression mechanism for IPv6 datagrams (LOWPAN\_HC1 and LOWPAN\_HC2) to reduce the relatively large IPv6 and UDP headers. However, LOWPAN\_HC1 and LOWPAN\_HC2 are insufficient for most practical uses of 6LoWPAN networks, since they are effective only for link-local unicast communication, where IPv6 addresses can be derived directly from IEEE 802.15.4 addresses. When communicating with devices external to the LoWPAN or in a route-over configuration where IP forwarding occurs within the LoWPAN, LOWPAN\_HC1 carries both IPv6 source and destination addresses in-line. The internet draft \cite{draft-hc-06} defines an encoding format, LOWPAN\_IPHC, for effective compression of unique local, global, and multicast IPv6 addresses based on shared contexts. In addition, it defines an encoding format, LOWPAN\_NHC, for arbitrary next header compression.

\subsection{HC1 Header Encoding}\label{sec:hc1}

Devices in the same 6LoWPAN network share some state.  This makes it possible to compress headers without explicitly building any compression context state.  The following IPv6 header values are expected to be common on 6LoWPAN networks: Version is IPv6; both IPv6 source and destination addresses are link local;  the IPv6 interface identifiers for the source or destination addresses can be inferred from the layer two source and destination addresses; the packet length can be inferred either from layer two or from the \texttt{datagram\_size} field in the fragment header; both the Traffic Class and the Flow Label are zero; and the Next Header is UDP, ICMP or TCP. The Hop Limit (8 bits) field is the only one that always needs to be carried. Fields, which do not match the described common case, have to be carried in-line.
The HC1 encoding allows to compress a 40 byte IPv6 header to 2 bytes. 

In addition to HC1, the HC2 encoding may be used, which allows to compress a UDP header to 4 octets instead of the original 8 octets. More details can be found in \cite{rfc4944}.

\subsection{IPHC Header Encoding}\label{sec:iphc}
The IPHC encoding format enables effective compression of the IPv6 header relying on information pertaining to the entire 6LoWPAN network. The encoding assumes the following common case parameters for 6LoWPAN communication: Version is $6$; Traffic Class and Flow Label are both zero; Payload Length can be inferred from lower layers from either the 6LoWPAN Fragmentation header or the IEEE 802.15.4 header; Hop Limit will be set to a well-known value by the source; addresses assigned to 6LoWPAN interfaces will be formed using the link-local prefix or a single routable prefix assigned to the entire 6LoWPAN network; addresses assigned to 6LoWPAN interfaces are formed with an interface identifier derived directly from either the 64-bit extended or 16-bit short IEEE 802.15.4 addresses. The compression mechanism is adapted for these values of the header fields and in such scenario the LOWPAN IPHC can compress the IPv6 header down to two octets with link-local communication.  When routing over multiple IP hops, IPHC can compress the IPv6 header down to 7 octets. 

In contrast to HC2, the NHC encoding used with IPHC provides a flexible and extensible mechanism for arbitrary header compression, not only for UDP, TCP, and ICMPv6. With NHC, chains of next headers can be encoded efficiently, which is not possible with HC1 and HC2. 

%%%
%	SNMP
%%%
\chapter{Simple Network Management Protocol}\label{ch:snmp}
Large networks have too many components to be managed by humans alone. Network devices have to maintain a large amount of management data such as configuration information,  operational state and statistics. Management information can be used to understand how a network performs, how devices in a network are configured and to change their configuration. The Simple Network Management Protocol (SNMP) \cite{rfc3410} is an application layer protocol that facilitates the exchange of management information between network devices. It exposes management data in the form of variables on the managed systems, which describe the system configuration. Since its first publication in 1988, the SNMP protocol has become a widely-used network management tool for IP-based networks.

Currently, there are three versions of SNMP defined. The first version (SNMPv1) is nowadays a historical IETF standard, although it is still widely supported by many vendors. One of the most important weaknesses of SNMPv1 is the lack of adequate mechanisms for securing the management function. Its security is based on a community string, which is a type of password transmitted in clear text. SNMPv2 extended the functionality of SNMPv1 and includes a number of improvements, such as additional protocol operations. A new security system was proposed, however, it was too complex and was not widely accepted. SNMPv3 addresses the security problems of the previous versions. The SNMPv3 architecture introduces a well defined extensible architecture and the User-based Security Model (USM) for message security.

The SNMP protocol is datagram-oriented and its implementation can be very lightweight \cite{draft-6lowpan-snmp}. It can fit resource-constrained devices very well. This makes it a perfect candidate as a management protocol for 6LoWPAN applications. In this chapter an overview of the SNMP protocol is given.

\section{Management Information Base}
SNMP itself does not specify which information is offered by a managed system. Management information, which can be accessed via SNMP, is viewed as a collection of managed objects in a virtual information store, called the Management Information Base (MIB). MIB modules describe the structure of the device's management information using a hierarchical namespace containing object identifiers (OID). Each OID identifies a variable that can be read or set via SNMP. Collections of related objects are defined in MIB modules written in the Structure of Management Information (SMI) data definition language, which is an adapted subset of the Abstract Syntax Notation One (ASN.1) language. A number of specific MIB modules has been defined as part of the SNMP suite specifying managed objects for the most common network management subjects.

\section{Operational Model}
In a simple case, two different types of hardware devices are defined: managed nodes and network management stations. Managed nodes are regular nodes on a network equipped with software to allow them to be managed using SNMP. A network management station is a designated network device that executes applications that monitor and control managed devices. Each device that participates in SNMP network management runs a piece of software called an SNMP entity. The SNMP entity is responsible for implementing all of the various functions of the SNMP protocol. The SNMP entity on a managed node consists of the SNMP agent, which implements the SNMP protocol, and the SNMP Management Information Base, which defines the types of information that the node provides via the SNMP protocol.


\section{Protocol Architecture}\label{snmp-arch}
The SNMP protocol has a modular architecture, which allows the evolution of the protocol and enables protocol extensions. The protocol architecture is composed of an SNMP engine and applications. An SNMP entity is an implementation of this architecture. The SNMP engine includes several subsystems communicating via defined abstract service interfaces. Abstract service interfaces describe the conceptual interfaces between various subsystems.  While the subsystems can be changed and extended over time, the interfaces are fixed.

\begin{figure}[htp]	
\begin{center}
    \includegraphics[scale = 0.6]{img/snmp-arch.pdf}
    \caption{Structure of an SNMP entity}   
	\label{fig:snmparch}
\end{center}
\end{figure}

According to the SNMP architecture defined in \cite{rfc3411}, the SNMP engine is composed of a dispatcher, a message processing subsystem, a security subsystem, an access control subsystem, and a transport subsystem (Figure \ref{fig:snmparch}). Each subsystem may include multiple concrete models providing different implementations of the same service. The dispatcher is the key part of an SNMP engine. It is responsible for controlling the data flow within an SNMP entity. When an SNMP message needs to be prepared or when data needs to be extracted from an SNMP message, the dispatcher delegates these tasks to a version-specific message processing model within the message processing subsystem. It also dispatches SNMP  protocol data units (PDUs) to SNMP applications. Each message processing model defines the format of a particular version of an SNMP message. Typically, the message processing subsystem supports three models for SNMPv1, SNMPv2c, and SNMPv3. The security subsystem provides security services such as authentication and privacy of messages. Authorization services are provided by the access control subsystem. The transport subsystem \cite{rfc5590} allows for multiple transport protocols to be used.

There are several types of defined applications (Figure \ref{fig:snmparch}), such as a command generator which monitor and manipulate management data, a command responder providing access to management data, a notification originator initiating asynchronous messages, a notification receiver processing these messages, and a proxy forwarder which forwards messages between entities. Applications may use the services provided by the SNMP engine. An SNMP entity which includes one or more command generator and notification receiver applications is called an SNMP manager. An SNMP entity containing one or more command responder and notification originator applications is called an SNMP agent.

\section{Message Format}\label{sec:messformat}
The SNMPv3 message (Figure \ref{fig:snmp-format}) contains the SNMP version, fields for global data (such as the message identifier, the maximum message size, the security model and the level of security), fields for the security model information and naming scope (context identifier and name), and finally the protocol data unit (PDU).
\begin{figure}[htp]	
\begin{center}
    \includegraphics[scale = 0.60]{img/snmpv3-message.pdf}
    \caption{SNMPv3 Message Format}   
	\label{fig:snmp-format}
\end{center}
\end{figure}

The SNMP Version field identifies the version of the message format. The message identifier (msgID) is used between two SNMP entities to coordinate request messages and responses and to coordinate the message processing by different subsystem models. The maximum message size (Max Size) is the maximum message size supported by the sender of the message, i.e., the maximum message size that the sender can accept when another SNMP engine sends an SNMP message. The Flag field contains several bit fields which control processing of the message. The security model field enables the concurrent support of multiple security models identifying which security model was used by the sender to generate the message. The security parameters field is used for communication between the security model modules in the sending and receiving SNMP engines. The contents and format of the data in this field are defined by the security model.

The naming scope contains a PDU and the context in which it has to be processed. The context engineID identifies the engine which realizes the managed objects referenced within the PDU, and the context name defines the particular context associated with the management information contained in the PDU of the message. These fields are followed by the PDU data.

The common format of protocol data units is shown in Figure \ref{fig:snmp-pdu}. This format is used for all operations described in Section \ref{sec:opetations}, except for the GetBulk request. The PDU is tagged with a number that identifies the type of the PDU. The request identifier is used to match requests with replies. It is generated by the device that sends a request and copied into this field in a response PDU by the responding SNMP entity. The error status tells the requesting SNMP entity the result of its request. A value of zero indicates that no error occurred; the other values indicate what sort of error happened. When error status is non-zero, the error index field points to the object generating the error, and has the value of zero in a request. The variable bindings is a set of name-value pairs identifying the MIB objects in the PDU, and in the case of messages other than requests, containing their values.
\begin{figure}[htp]	
\begin{center}
    \includegraphics[scale = 0.60]{img/snmp-pdu.pdf}
    \caption{SNMP Common PDU Format}   
	\label{fig:snmp-pdu}
\end{center}
\end{figure}


\section{Protocol Operations}\label{sec:opetations}
As described in Section \ref{sec:messformat}, an SNMP message encapsulates a PDU which specifies the operations performed by the receiving SNMP engine. The SNMP protocol defines PDU formats for the following operations: \texttt{Get}, \texttt{GetNext}, \texttt{GetBulk}, \texttt{Response}, \texttt{Set}, \texttt{Trap}, \texttt{Inform} and \texttt{Report} (Figure \ref{fig:snmp-operations}). 

\begin{figure}[htp]	
\begin{center}
	\label{fig:snmp-operations}
    \includegraphics[scale = 0.80]{img/snmp-operations.pdf}
    \caption{SNMP Operations}   
\end{center}
\end{figure}


The \texttt{Get} request initiated by a manager allows to access and retrieve the value of one or more instances of management information. The agent processes each variable binding in the variable-binding list of the received \texttt{Get} PDU by resolving their values and produces a \texttt{Response} PDU. The \texttt{Response} PDU is sent back to the manager. If the processing of any variable binding fails, the details of the error are reflected in the the error status and error index fields in the \texttt{Response} PDU. The \texttt{GetNext} operation retrieves the value of the next existing MIB instances in lexicographic order. Successive \texttt{GetNext} operations can be used to walk the MIB instances without prior knowledge about the MIB structure. The \texttt{GetBulk} operation is a generalization of the \texttt{GetNext} operation where the agent performs a series of \texttt{GetNext} operations internally. This makes it easier to acquire large amounts of related information without initiating repeated \texttt{GetNext} operations. The manager can set values for the managed objects by using the \texttt{Set} operation.

The \texttt{Trap} is sent by an agent to a manager and indicates that an event has occurred or a certain condition is present. There is no confirmation associated with this notification delivery mechanism. The confirmed notification delivery mechanism is provided by the \texttt{Inform} operation. Finally, the \texttt{Report} operation can be used internally to allow SNMP engines to communicate with each other for error notifications and clock synchronization.

\section{Security Models}
SNMPv1 and SNMPv2c provide only trivial security based on a clear-text community string and lack of adequate mechanisms for securing the management function. The security issues are addressed in SNMPv3 where the User-based Security Model (USM) \cite{rfc3414} is defined that provides security services for authentication, timeliness and privacy. Another security model for the SNMP protocol is the Transport Security Model defined in \cite{rfc5591} that makes use of existing commonly deployed security infrastructures providing lower-layer secure transports. 

\subsection{User-based Security Model}\label{sec:usm}
The USM security model is split into three modules: the authentication module provides data integrity and data origin authentication; the timeliness module provides delay and replay protection; the privacy module provides protection against disclosure of the message payload. The timeliness module is fixed, while multiple authentication and privacy modules are possible, which implement specific authentication and privacy protocols.

The USM provides three levels of security:
\begin{enumerate}
\item[1)] \texttt{noAuthNoPriv} mode provides no authentication and no encryption services.
\item[2)] \texttt{authNoPriv} mode provides message authentication, message integrity, and timeliness checking services but no encryption.
\item[3)] \texttt{authPriv} mode message provides authentication, message integrity, timeliness checking services and encryption of the payload.
\end{enumerate} 


\section{Transport Mappings}
Once an SNMP message has been generated, it is sent using the protocols at the levels below the application layer where SNMP resides. The document \cite{rfc3417} defines the transport of SNMP messages over various protocols. Even though several mappings are defined, the mapping onto UDP over IPv4 is preferred for systems supporting IPv4.

When the UDP over IPv4 transport is in use, each SNMP message is serialized (i.e., encoded according to the Basic Encoding Rules (BER) \cite{ber}) onto a single UDP datagram. Since UDP does not guarantee data delivery, a request or reply can be lost in transit. Only the device that initially sends a request can know if there is a problem with the transport. This puts the responsibility for retransmission on the part that sends the request message.  Two well-known UDP port numbers are reserved for SNMP. All devices that are set up to listen for SNMP requests, both agents and managers, listen on port 161. The second UDP port number is 162, which is reserved for SNMP notifications.

\chapter{Related Work}\label{ch:relatedwork}
This chapter gives a short overview of the current approaches on network management in 6LoWPANs. Section \ref{sec:lnmp} provides the details of the LoWPAN Network Management Protocol. The Simple Network Management Protocol for 6LoWPAN is discussed in Section \ref{sec:6lowpan-snmp}. 

\section{LNMP}\label{sec:lnmp}
LoWPAN Network Management Protocol (LNMP) presented in \cite{lnmp} is a management architecture for 6LoWPAN based networks. The architecture emphasizes on reduction of communication cost in order to increase the network lifetime. One of the goals of LNMP is interoperability with SNMP. However, SNMP was considered to be quite bulky both in terms of complexity and communication for resource-constrained devices.

In the proposed architecture, SNMP is supported on the IPv6 network side only. The 6LoWPAN gateway acts as a proxy between SNMP and the local management framework. Whenever an SNMP request arrives at the gateway, it is translated from SNMP to a simplified query format. The gateway sends a UDP based query that contains identifiers of the objects to be retrieved to the destination device's agent. Similarly, when a reply arrives at the gateway, it is translated back to the SNMP format, and an SNMP response packet is sent back to the source of the requested object value. The gateway is also responsible for responding to requests for objects whose values are constant for the whole network. The proposed management architecture was implemented for the Atmel ATmega 128L microcontroller.

The advantage of LNMP is efficiency and reduced overhead on the network. However, it does not provide the native support of SNMP, and at the gateway similar protocol operations have to be re-implemented. The gateway is a single point of failure in this architecture and has a large computational overhead caused by the conversion between protocols. Security implications are not considered in the paper \cite{lnmp}. 

\section{6LoWPAN-SNMP}\label{sec:6lowpan-snmp}
Simple Network Management Protocol for 6LoWPAN (6LoWPAN-SNMP) \cite{6lowpan-snmp} is an extended modification of the Simple Network Management Protocol optimized for the resource-constrained nature of the low-power and low data-rate wireless networks. 6LoWPAN-SNMP utilizes several techniques to reduce the amount of SNMPv1 and SNMPv2c traffic on the 6LoWPAN network. First, the length of the SNMP message header fields is optimized. Second, the object identifier delta compression mechanism described in \cite{snmp-payload-comression} is applied to compress the object identifier field in the PDU variable bindings. Extended protocol operations such as PeriodicGetRequest and broadcast/multicast SNMP messages are proposed, which effectively reduce the number of radio packets transmitted over the network. Instead of sending request messages every time, multiple periodic responses can be initiated by sending a singe PeriodicGetRequest message. A StopPeriodicGet message can be transmitted to stop the periodic responses. The current SNMP standard  is designed only for point-to-point communication and network management systems (NMS) collect management information mainly by polling each host in the network. The proposed broadcast Get Request message allows to reduce the overhead of polling individual nodes in the network. A NMS injects a broadcast Get Request message into the network and every host immediately responds with a Response message to the NMS. However, broadcasting SNMP messages can not be applied in situations where each mote uses different OIDs for the same information (e.g., when table rows are indexed differently on different motes).

Compatibility with the standard SNMP is achieved by a proxy located on the gateway. The proposed mechanism is implemented on actual hardware platforms using the open-source Net-SNMP library and the Berkeley 6LoWPAN on the TinyOS 2.1. 6LOWPAN-SNMP does not support SNMPv3 and its authentication and encryption schemes.

%%%
%	Hardware platform & OS
%%%
\chapter{Targeted Platform}\label{ch:hardware}
The hardware platform chosen for the project, the AVR Raven board, is described in Section \ref{ch:raven}. Section \ref{sec:netset} gives the details of the network setup used in the project. In Section \ref{ch:contiki}, the Contiki operating system is introduced providing the details of its networking capabilities.

\section{AVR Raven Board}\label{ch:raven}
The AVR Raven board \cite{raven}, produced by the Atmel Corporation, includes two microcontrollers (MCUs), one radio transceiver chip and an LCD display. The ATmega1284PV MCU runs the communication while the LCD display is driven by the ATmega3290PV. The wireless communication is enabled by the AT86RF230 transceiver.

Both ATmega1284PV and ATmega3290PV are modified Harvard architecture 8-bit RISC single chip MCUs with program and data stored in separate physical memory systems and different address spaces. Flash, EEPROM, and SRAM are all integrated onto a single chip. Program instructions are stored in non-volatile flash memory. Each instruction takes one or two 16-bit words. The MCUs of this family ensure minimal power consumption. 

The ATmega1284PV runs at 20 MHz and has 16 kB of SRAM, 128 kB of flash program memory and  4 kB of EEPROM. It embeds two 16-bit timers, two 8-bit timers and one real time counter. The ATmega3290PV runs at 16 MHz and has 2 kB of SRAM, 32 kB of flash memory and 1 kB of EEPROM. The universal synchronous and synchronous serial receiver and transmitter (USART) is used as an inter processor communication bus which enables communication between two MCUs. 

\begin{figure}[htp]	
\begin{center}
    \includegraphics[scale = 0.7]{img/raven.jpg}
    \caption{AVR Raven board}
	\label{fig:raven}
\end{center}
\end{figure}

The AT86RF230 is a 2.4 GHz radio transceiver targeted for IEEE 802.15.4 and 6LoWPAN applications. It supports  automatic frame acknowledgement and retransmission, automatic CSMA-CA and data transfer speeds of up to 250 kbps. However, no security operation is available.

The AVR Raven board can be powered either from batteries or an external 5 to 12 Volts DC source. The board has been designed to run from two 1.5V LR44 battery cells. 

A wide variety of third-party programming and debugging tools are available for the AVR. In this project the Atmel JTAGICE mkII programming platform has been used.



\section{Network Setup}\label{sec:netset}
The network setup used in the project includes a PC acting as an IPv6 router with an 802.15.4 interface and an AVR Raven board acting as an IPv6 host. The AVR RZUSBstick, a USB stick with a 2.4 GHz transceiver, is used to provide the PC with an 802.15.4 interface. It enables the communication between the PC and AVR Raven board devices.

\begin{figure}[htp]	
\begin{center}
    \includegraphics[scale = 0.7]{img/stick.jpg}
    \caption{AVR RZUSBstick}
	\label{fig:stick}
\end{center}
\end{figure}

\section{Contiki Operating System}\label{ch:contiki}
Contiki \cite{contiki} is an open source, highly portable, multi-tasking operating system for memory-constrained networked embedded systems and wireless sensor networks. It consists of an event-driven kernel on top of which application programs are dynamically loaded and unloaded at runtime. The Contiki code footprint is on the order of kilobytes and memory usage can be configured to be as low as tens of bytes. It is written in the C programming language and is freely available under a BSD-style license.

Contiki processes use protothreads that provide a linear, thread-like programming style on top of the event-driven kernel. The main advantage of protothreads over ordinary threads in memory constrained systems is that they are very lightweight and do not require their own stacks. A protothread requires only two bytes of memory. All protothreads share the same stack and context switching is done by stack rewinding.

Contiki contains two communication stacks: Rime and uIP. Rime is a lightweight communication stack designed for low-power radios, which provides a wide range of communication primitives. uIP is a small RFC-compliant TCP/IP stack. While the uIP stack provides IPv4 connectivity, the IPv6 implementation is a part of uIPv6 \cite{durvy08making} (shown in Figure \ref{fig:uip}). uIPv6 does not depend on any particular MAC or link layer and can run over 802.15.4/6LowPAN, 802.11 or Ethernet. SICSLoWPAN is the 6LoWPAN layer implementation for Contiki used to format packets between the 802.15.4 and the IPv6 layers. It is called by the MAC process when a 6lowpan packet is received, and by the \texttt{tcpip} process when an IPv6 packet needs to be sent. The implementation supports header compression mechanisms defined in RFC4944 \cite{rfc4944} and the IPHC compression mechanism defined in \cite{draft-hc-06}.

\begin{figure}[htp]	
\begin{center}
    \includegraphics[scale = 0.6]{img/uipv6.pdf}
    \caption{The uIPv6 stack}
	\label{fig:uip}
\end{center}
\end{figure}

A complete IPv6/6lowpan/802.15.4 Contiki system requires around 40 kB of ROM and 10 kB of RAM.


\chapter{Implementation}\label{ch:snmpv1-impl}
In the course of this project, the SNMP protocol has been implemented for the Contiki Operating System. The implementation includes SNMPv1 and SNMPv3 message processing models and supports \texttt{Get}, \texttt{GetNext} and \texttt{Set} operations. The USM security model has been implemented and supports the HMAC-MD5-96 authentication and CFB128-AES-128 symmetric encryption protocols. Management data are accessed via the MIB module, which provides an interface to define and configure accessible managed objects. The standard specifies that SNMP entities must accept messages up to at least 484 bytes in size, which is the maximum message size supported by the implementation. The implementation has been accomplished in the C programming language and uses network primitives provided by the Contiki uIPv6 stack.

Section \ref{sec:design} describes the implementation design principles. In Section \ref{sec:modules} an overview of modules and interfaces is presented. Section \ref{sec:proc} provides the details of the processing of an incoming SNMP message. Section \ref{sec:ds} describes the data structures used in the implementation. The implementation details of the User-based Security Model are discussed in Section \ref{sec:usm}. Section \ref{sec:mib} describes the interfaces and data structures of the MIB module. Section \ref{sec:conf} provides the configuration details of the agent.

\section{Design Principles}\label{sec:design}
The main challenge of the project is to run on the AVR Raven board hardware platform and fit its resource limitations. The Contiki operating system uses up to 10 kB of RAM and 40 kB of ROM of the targeted platform, therefore, the SNMP agent should not require more than 88 kB of ROM and 6 kB of RAM. The preference is given to easily readable and maintainable source code over memory efficient hard to understand programming constructs and hacks. Due to the small amount of available RAM memory, necessary data structures have to be optimized and designed very accurately. Since the amount of ROM memory provided by the hardware platform is significantly larger than the amount of RAM, ROM memory should be preferred for storing read-only data.

The implementation does not follow the SNMP modular architecture exactly how it is defined in \cite{rfc3411}. For such resource-constrained devices, this architecture is too bulky and, therefore, it would result in an inefficient implementation. In this project, the architecture and the abstract service interfaces it describes have been simplified to minimize the consumption of resources. 

\section{Modules  and Interfaces}\label{sec:modules}
The implementation is divided into several logical subsystems interacting with each other via provided interfaces. Each subsystem handles a separate function, which allows to easily extend the implementation. 

According to the SNMP architecture described in Section \ref{snmp-arch}, the key subsystem is a dispatcher. The dispatcher interface is defined in the file \texttt{dispatcher.h} and declares the \texttt{dispatch()} function:

\begin{mylisting}
\begin{verbatim}
   s8t dispatch(u8t* const input, const u16t input_len, 
                u8t* output, u16t* output_len, const u16t max_output_len);
\end{verbatim}
\end{mylisting}

The first two arguments of this function are a pointer to an incoming SNMP message in the BER encoding format and the length of the message. The incoming message is processed and the resulting BER-encoded response message is stored to the \texttt{output} buffer. The \texttt{output\_len} and \texttt{max\_output\_len} are the length of the response and the \texttt{output} buffer respectively. If the processing has finished successfully, the function returns a zero value and nonzero error code otherwise.

The message processing subsystem provides models for SNMPv1 and SNMPv3. The interfaces of these models are defined in files \texttt{msg-proc-v1.h} and \texttt{msg-proc-v3.h} respectively and each of them declares two functions:

\begin{mylisting}
\begin{verbatim}
   s8t prepareDataElements_vX(u8t* const input, const u16t input_len, 
                           u16t* pos, message_vX_t* request);

   s8t prepareResponseMessage_vX(message_vX_t* message, 
                                 u8t* output, u16t* output_len, 
                                 const u8t* const input, u16t input_len, 
                                 const u16t max_output_len),
\end{verbatim}
\end{mylisting}
where \texttt{X} is the SNMP version. The \texttt{prepareDataElements\_vX()} function extracts the abstract data elements from an incoming SNMP message and populates the fields of the version-specific \texttt{message\_t} structure. The data structures are discussed in more details in Section \ref{sec:ds}. The \texttt{prepareResponseMessage\_vX()} function prepares an outgoing SNMP response message.  It takes a version-specific \texttt{message\_t} structure as input and serializes it to a BER-encoded SNMP message. 

The security subsystem provides an implementation of the User-based Security Model, discussed in Section \ref{sec:usm}. The model interface is defined in the file \texttt{usm.h} and declares the following functions:

\begin{mylisting}
\begin{verbatim}
   s8t processIncomingMsg_USM(u8t* const input, const u16t input_len, 
                              u16t* pos, message_v3_t* request);

   s8t prepareOutgoingMsg_USM(message_v3_t* message, u8t* output, 
                              u16t output_len, s16t* pos);

   s8t authenticate(message_v3_t* message, u8t* output, u16t output_len);
\end{verbatim}
\end{mylisting}

The \texttt{processIncomingMsg\_USM()} function extracts model specific security parameters from an incoming BER-encoded SNMP message and stores them to the fields of the \texttt{message\_v3\_t} structure. It is also responsible for authentication of the message and decryption of the scoped PDU. The \texttt{prepareOutgoingMsg\_USM()} function adds model specific security parameters to an outgoing SNMP message and encrypts the scoped PDU data if necessary. The \texttt{authenticate()} function computes the message authentication code for a message which is ready to be sent.

The command responder application supports \texttt{Get}, \texttt{GetNext} and \texttt{Set} operations. The interface of the command responder is defined in the file \texttt{cmd-responder.h} and declares one function: 

\begin{mylisting}
\begin{verbatim}
   s8t handle(message_t* message);
\end{verbatim}
\end{mylisting}

This function processes an SNMP request stored in a generic \texttt{message\_t} structure. In order to access management data, the MIB module is used. For this purpose the following functions are declared in the file \texttt{mib.h}:

\begin{mylisting}
\begin{verbatim}
   mib_object_t* mib_get(varbind_t* req);

   mib_object_t* mib_get_next(varbind_t* req);

   s8t mib_set(mib_object_t* object, varbind_t* req);
\end{verbatim}
\end{mylisting}

The \texttt{mib\_get()} function retrieves the value of the object named in the variable binding. If there is no such object, a zero value is returned and a pointer to the object otherwise. The \texttt{mib\_get\_next()} function retrieves the value of the lexicographical successor to the object named in the variable binding. If there is no such object, a zero value is returned. The \texttt{mib\_set()} function assigns the value specified in the variable binding to the object.

The BER module defines a number of primitives for BER encoding and decoding. The interfaces of these functions are declared in the file \texttt{ber.h}. The module deals with integers, strings, object identifiers and sequences. It also defines encoding and decoding rules for the SNMP PDU.

\section{Message Processing}\label{sec:proc}
The SNMP agent is run as a separate process defined in the file \texttt{snmpd.c}. At startup, the process accomplishes initialization of the Management Information Base and starts listening a specific UDP port for incoming SNMP request. 

Upon receipt of a message from the network, it is passed to the dispatcher by calling the \texttt{dispatch()} function (shown in Figure \ref{fig:oper}). The dispatcher determines the version of the SNMP message and calls the version-specific \texttt{prepareDataElements\_vX()} function of the message processing model. The message processing model decodes the BER-encoded message and populates the fields of the version-specific \texttt{message\_t} structure. In case the USM security model is used, the message processing model calls the \texttt{processIncomingMsg\_USM()} function, which performs the timeliness check, authenticates and decrypts the message if necessary. 

Once the control has been returned to the dispatcher, the \texttt{handle()} function of the command responder is called. The command responder processes the request by calling the API functions of the MIB module, described in Section \ref{sec:mib}. 

Once the request has been processed, the dispatcher calls the version-specific \texttt{prepareResponseMessage\_vX()} function, which performs BER-encoding of the response message. In case of using the USM security model, the \texttt{prepareOutgoingMsg\_USM()} and \texttt{authenticate()} functions are called to encode the security parameters and encrypt the scoped PDU.

The dispatcher returns the generated response message, which is sent back to the originator.

\begin{figure}[ht]	
\begin{center}
    \includegraphics[scale = 0.6]{img/oper1.pdf}
    \caption{Processing of an incoming SNMPv3 message}
	\label{fig:oper}
\end{center}
\end{figure}

\section{Data structures}\label{sec:ds}
The data structures used in the processing of an SNMP request are defined in the file \texttt{snmp.h}. An incoming BER-encoded SNMP message is decoded and stored into a version-specific \texttt{message\_t} structure. While processing a message, the same data structures are used to generate a response.

The generic \texttt{message\_t} structure contains the \texttt{version} and \texttt{pdu} members common for both SNMPv1 and SNMPv3:
\begin{mylisting}
\begin{verbatim}
    typedef struct {
        u8t     version;
        pdu_t   pdu;
    } message_t;
\end{verbatim}
\end{mylisting}

The \texttt{message\_v3\_t} structure extends \texttt{message\_t} with SNMPv3 and USM specific members such as \texttt{msgId}, \texttt{msgFlags}, \texttt{contextEngineID}, \texttt{contextName}, \texttt{msgAuthoritativeEngineID}, \texttt{msgAuthoritativeEngineBoots}, \texttt{msgAuthoritativeEngineTime}, \texttt{msgUserName}, \texttt{msgAuthenticationParameters} and \texttt{msgPrivacyParameters}. The values of string type message fields are not copied from the message buffer. Instead, they are of the \texttt{ptr\_t} type, which is a structure containing a pointer to the first byte of the value and its length. This allows to reuse the message buffer and save memory.

The members of the \texttt{pdu\_t} structure correspond to the fields of the SNMP PDU:
\begin{mylisting}
\begin{verbatim}
    typedef struct {
        u8t                  request_type;
        u8t                  response_type;
        s32t                 request_id;
        u8t                  error_status;
        u8t                  error_index;
        varbind_list_item_t* varbind_first_ptr;
        u16t                 varbind_index;
    } pdu_t;
\end{verbatim}
\end{mylisting}
The \texttt{response\_type} member specifies the response PDU type and can be either \texttt{Response-PDU} or \texttt{Report-PDU}. The \texttt{varbind\_index} member specifies the byte in the request message buffer where the variable binding list starts. It is used to generate a response when an error occurs and the \texttt{error\_status} field has a none-zero value. In this case, the variable-bindings field of the response PDU is re-formatted with the same values as in the received request and can be copied from the request message buffer. The \texttt{varbind\_first\_ptr} member of the \texttt{varbind\_list\_item\_t} type points to the head of the linked list of variable bindings.

\begin{mylisting}
\begin{verbatim}
    typedef struct varbind_list_item_t {
        varbind_t                    varbind;
        struct varbind_list_item_t*  next_ptr;
    } varbind_list_item_t;
\end{verbatim}
\end{mylisting}

A variable binding is stored in an instance of the \texttt{varbind\_t} structure:
\begin{mylisting}
\begin{verbatim}
    typedef struct varbind_t {
        ptr_t*              oid_ptr;
        u8t                 value_type;
        varbind_value_t     value;
    } varbind_t;
\end{verbatim}
\end{mylisting}

In the implementation OIDs are not decoded and stored in the BER encoding format, which allows to save a significant amount of memory space. The \texttt{ptr\_t} type is used to represent an OID in the \texttt{varbind\_t} structure and specifies a sequence of bytes in the received message buffer where the OID is stored. The \texttt{varbind\_value\_t} type represents the value of the variable binding:

\begin{mylisting}
\begin{verbatim}
    typedef union {
        s32t         i_value;
        u32t         u_value;
        ptr_t        p_value;
    } varbind_value_t;
\end{verbatim}
\end{mylisting}

The \texttt{i\_value} and \texttt{u\_value} members are used for signed and unsigned integer-based values respectively, while \texttt{p\_value} corresponds to string-based values and OIDs.

\section{User-based Security Model}\label{sec:usm}
The User-based Security Model with the HMAC-MD5-96 authentication and the CFB128-AES-128 symmetric encryption protocols is supported by the agent. The implementation is based on the cryptographic primitives provided by the OpenSSL library \cite{openssl}. The MD5 cryptographic hash function has been ported to the AVR Raven platform without significant changes. The source code is available in files \texttt{md5.h} and \texttt{md5.c}. The HMAC-MD5-96 calculation is implemented in the file \texttt{usm.c}.
The implementation of the AES cipher algorithm provided by the OpenSSL library uses an array of constants of 4096 bytes. This would constitute 25\% of the overall RAM available on the targeted hardware platform. While adapting the AES implementation, the constants have been moved to the read-only flash program memory.

The HMAC-MD5-96 calculation and CFB128-AES-128 encryption uses localized authentication and encryption keys respectively. These keys are hardcoded in the file \texttt{keytools.c}. In order to construct a localized key based on the engine identifier and password, a \texttt{keygen} command-line tool has been developed.

\section{Management Information Base}\label{sec:mib}
The MIB module provides access to management data. The interface of this module is defined in the file \texttt{mib.h} and allows to add and configure managed objects accessible via SNMP. Initially, the MIB has no objects in it. The definition of managed objects is accomplished in the implementation of the \texttt{mib\_init()} function declared in the file \texttt{mib-init.h}. All objects have to be added to the MIB in ascending order of their object identifiers.

Two types of managed objects are supported: scalar and tabular. Scalar objects define a single object instance, while tabular objects define multiple related object instances that are grouped in MIB tables. The number of rows in a table is not fixed at compile time and can vary over time.

\subsection{Interfaces}
A managed object can be added to the MIB by calling either the \texttt{add\_scalar()} or \texttt{add\_table()} function, for scalar and tabular objects respectively.

\begin{mylisting}
\begin{verbatim}
    add_scalar(ptr_t* oid, u8t attrs, u8t value_type, void* value, 
               get_value_t gfp, set_value_t svfp);
               
    add_table(ptr_t* oid_prefix, 
              get_value_t gfp, get_next_oid_t gnofp, set_value_t svfp);
\end{verbatim}
\end{mylisting}

The first parameter of the \texttt{add\_scalar()} function is the OID of the managed object. In case of the tabular object, this is the longest OID prefix common for all instances. The \texttt{attrs} parameter specifies the attributes of the managed object. The \texttt{FLAG\_ACCESS\_READONLY} value of this attribute can be used for defining read-only objects. The type of the object and its default value are specified by passing \texttt{value\_type} and \texttt{value}.

User-defined functions for getting and setting the value of an object can be specified via the \texttt{gfp} and \texttt{svfp} arguments. These function types are defined in the following way:

\begin{mylisting}
\begin{verbatim}
    typedef s8t(*get_value_t)(mib_object_t* object, u8t* oid, u8t len);
    
    typedef s8t(*set_value_t)(mib_object_t* object, u8t* oid, u8t len,
                              varbind_value_t value);    
\end{verbatim}    
\end{mylisting}
The \texttt{object} argument is a pointer to the managed object. The \texttt{oid} and \texttt{len} arguments are passed only for tabular objects and specify the BER-encoded OID of the object instance and its length.  The last argument of the setter function is the value to set.

The \texttt{add\_table()} function requires one more argument, \texttt{gnofp}, of the \texttt{get\_next\_oid\_t} function type:
\begin{mylisting}
\begin{verbatim}
   typedef ptr_t* (*get_next_oid_t)(mib_object_t* object, u8t* oid, u8t len);
\end{verbatim}    
\end{mylisting}
A function of this type has to resolve the \texttt{GetNext} request for the given OID and tabular object. If the OID is a lexicographical successor of the object then \texttt{0} value is returned. 

\subsection{Data Structures}\label{sec:mib-ds}
Each managed object is represented in the MIB by an instance of the \texttt{mib\_object\_t} structure.
\begin{mylisting}
\begin{verbatim}
    struct mib_object_t {
        u8t attrs;
        varbind_t varbind;
        get_value_t get_fnc_ptr;
    #if ENABLE_MIB_TABLE
        get_next_oid_t get_next_oid_fnc_ptr;
    #endif
        set_value_t set_fnc_ptr;
    #ifndef MIB_SIZE
        struct mib_object_t* next_ptr;
    #endif
    };
\end{verbatim}
\end{mylisting}
The \texttt{attrs} member specifies the attributes of the object. The \texttt{varbind} member holds the OID of the object and its value. The \texttt{get\_fnc\_ptr} and \texttt{set\_fnc\_ptr} members are pointers to the user-defined getter and setter functions respectively. In case of enabled tabular objects, two additional bytes are required for the \texttt{get\_next\_oid\_fnc\_ptr} pointer for every managed object. Tabular objects is an optional feature and can be disabled by changing the value of the \texttt{ENABLE\_MIB\_TABLE} macro definition.

The OID of a managed object is an array of bytes which does not change its value over time. By default, such arrays are handled as all other initialized variables: they occupy RAM, and occupy the same amount of flash ROM so they can be initialized to the actual value by startup code. This is a waste of RAM, which is critical for resource constrained platforms. Such data can be moved out to flash ROM. However, to access the data stored in the flash ROM special functions have to be used, which results in additional complexity. The implementation allows to store OIDs either in RAM or flash ROM. This can be defined at compile time, by switching the value of the \texttt{ENABLE\_PROGMEM} macro definition between \texttt{0} and \texttt{1}.
			
The implementation supports two ways to organize the storage of managed objects by using either an array or a linked list. In the first case, the number of objects has to be predefined at compile time by using the \texttt{MIB\_SIZE} macro definition, otherwise a linked list is used. In the latter case, every managed object requires two extra bytes for the \texttt{next\_ptr} member.

\subsection{MIB Modules}
The hierarchical structure of the \texttt{SNMPv2-MIB}, \texttt{IF-MIB}  and \texttt{ENTITY-SENSOR-MIB} modules has been implemented for the AVR Raven board platform.  The \texttt{SNMPv2-MIB} defines managed objects which describe the behavior of an SNMP entity. The \texttt{IF-MIB} provides access to information related to managing network interfaces. It exposes counters of packets received on and  transmitted out an interface. In order to obtain such statistical data, the Contiki radio driver for the AVR platform has been adapted. The managed objects of the \texttt{ENTITY-SENSOR-MIB} provides access to physical sensors. The readings of the temperature sensor can be obtained via the objects of this module.

\subsection{BER Encoder}\label{ch:oid-encoder}
When adding a managed object to the MIB, the OID of the object has to be specified. As mentioned above, the implementation deals with OIDs encoded using the BER encoding format, which allows to save memory and avoid OID decoding. Therefore, OIDs of managed objects have to be defined encoded in BER.

For this reason, a BER encoder tool has been developed. The encoder takes an OID in the dot notation as an argument and outputs an array in the C programming language containing the OID encoded in BER. The generated array can be used in the definition of the managed object.

\section{Configuration}\label{sec:conf}
Configuration of the agent can be accomplished by modifying the file \texttt{snmpd-conf.h}. The maximum supported length of a message is defined by the \texttt{MAX\_BUF\_SIZE} macro definition. In order to enable and disable message processing models, the values of the \texttt{ENABLE\_SNMPv1} and \texttt{ENABLE\_SNMPv3} macro definitions can be switched between \texttt{1} and \texttt{0}. Disabling a message processing model allows to reduce memory usage of the agent. The authentication and privacy protocols can be disabled by changing the values of the \texttt{ENABLE\_AUTH} and \texttt{ENABLE\_PRIVACY} macro definitions respectively. The \texttt{TIME\_WINDOW} macro definition allows to configure the  length of the USM time window. The user name, engine identifier and community string can be also changed in this file.

\chapter{Evaluation}\label{ch:eval}
The implementation has been tested for interoperability with the \texttt{snmpget}, \texttt{snmpgetnext}, \texttt{snmpset} and \texttt{snmpwalk} applications from the Net-SNMP suite \cite{netsnmp}. The network setup used for the experiments is described in Section \ref{sec:netset}. All measurements reported in this chapter were made with Contiki 2.4 using the IPHC header compression mechanism. Due to extreme resource limitations of the targeted platform, it is essential to measure the memory usage of the agent. The memory usage estimations are presented in Section \ref{sec:memory}. 
The response latency has been measured for the agent against different SNMP versions, security levels and operations. Section \ref{sec:latency} presents the results of the measurements. 

\section{Memory and Code Footprint}\label{sec:memory}
Due to the limited memory resources of the targeted platform, the RAM and flash ROM used by the agent are important parameters that have to be evaluated. However, RAM usage is hard to measure because of the variable size of the stack and the heap used for dynamic memory allocation. In this section I present memory usage estimations obtained by using three different approaches.

\subsection{Flash ROM and Static Memory Usage}\label{sec:foot}
In the first approach, which allows to determine the flash ROM and static memory usage, the avr-size utility was employed. We are interested in measuring the memory used only by the agent and not by the whole program that also includes the Contiki operating system. To achieve this, we first compile the source code of Contiki  with the agent and measure the size of the output object file using the avr-size utility. Then, the same procedure is repeated for Contiki without the agent. The total memory used by the agent is obtained by a simple subtraction. The full implementation uses 31220 bytes of ROM, which is around 24\% of the available ROM on the targeted platform, and 235 bytes of statically allocated RAM. In case SNMPv1 is only enabled, the agent uses 8860 bytes of ROM (about 7\% of available ROM) and 43 bytes of statically allocated RAM.

In a similar way, I measured the code and memory footprint of each module of the agent. Table \ref{tab:avr-size} shows the detailed breakdown of the measurements.

\begin{table}[ht]
\begin{center}
\begin{tabular}{|l|r|r|}
\hline
Module & \ \ Flash ROM\ \ \ & \ RAM (static)\ \\
\hline
snmpd.c & 172 & 2\\
dispatch.c & 1076 & 26\\
msg-proc-v1.c & 634 & 6\\
msg-proc-v3.c & 1184 & 30\\
cmd-responder.c & 302 & 0\\
mib.c & 1996& 6\\
ber.c & 4264 & 3 \\
usm.c & 1160 & 122\\
aes\_cfb.c & 9752 & 40\\
md5.c & 10264 & 0\\
utils.c & 416 & 0\\
\hline
\end{tabular}
\caption{Flash ROM and static memory usage for the agent (bytes).}
\label{tab:avr-size}
\end{center}
\end{table}

As can be seen from the table, the cryptographic primitives occupy a significant amount of flash ROM.
The AES and MD5 implementations constitute around 31\% and 33\% respectively of the agent code size. Almost half of the ROM occupied by the AES implementation is used to store constants. The MD5 implementation intensively uses macro definitions for transformations which results in a huge code size. Using functions instead of them could reduce the code size, but would also effect the performance. It is worth to mention that the cryptographic primitives were ported from the OpenSSL library and are not optimized for embedded platforms.

The USM security model occupies almost half of the agent statically allocated RAM. This RAM is used to store localized keys and OIDs of the error indication counters.

\subsection{Stack}\label{sec:stack}
An experimental approach has been taken to estimate the stack size used by the agent to process a request. Upon receipt of an incoming SNMP message, the memory region allocated to the program stack is filled with a specific bit pattern.  When the processing has been finished, the stack is examined to see how much of it is overwritten. 

Table \ref{tab:stack-size} presents the maximum stack size observed during experiments for different versions of SNMP and security modes used. Most of the stack is occupied by the response message buffer of 484 bytes.
The SNMPv1 and SNMPv3 with \texttt{noAuthNoPriv} security level use approximately the same stack size, which constitutes around 4\% of the available RAM. When authentication and privacy are enabled, the stack grows up to 1144 bytes, which is about 7\% of RAM on the targeted platform.
\begin{table}[ht]
\begin{center}
\begin{tabular}{|c|l|r|}
\hline
Version & Security mode & Max. stack size\\
\hline
v1 & -- &                    688\\
v3 & noAuthNoPriv &       708\\
v3 & authNoPriv   &      1140\\
v3 & authPriv     &      1144\\
\hline
\end{tabular}
\caption{The experimental results for the  maximum stack size. The measurements are given in bytes.}
\label{tab:stack-size}
\end{center}
\end{table}

\subsection{Heap}\label{sec:heap}
Memory for the data structures used to store the fields of an SNMP message and discussed in Section \ref{sec:ds} is allocated from the heap using the \texttt{malloc} function. 

Table \ref{tab:messaget} provides a memory estimation for the \texttt{message\_t} structure. 
\begin{table}[ht]
\begin{center}
\begin{tabular}{|l|r|}
\hline
Member &  Size (bytes)\\
\hline
version  &	 1\\
pdu.request\_type & 1\\
pdu.response\_type & 1\\
pdu.request\_id & 4\\
pdu.error\_status & 1\\
pdu.error\_index & 1\\
pdu.varbind\_first\_ptr & 2\\
pdu.varbind\_index & 2\\
\hline
Total & 13\\ 
\hline
\end{tabular}
\caption{Memory estimation for the \texttt{message\_t} structure.}
\label{tab:messaget}
\end{center}
\end{table}

Each variable binding is stored in a linked list as an instance of the \texttt{varbind\_list\_item\_t} structure. In addition to the memory calculation shown in Table \ref{tab:listitem}, a variable binding uses 4 more bytes for an instance of the \texttt{ptr\_t} structure which points to the OID stored in the message buffer.

\begin{table}[ht]
\begin{center}
\begin{tabular}{|l|r|}
\hline
Member &  Size (bytes)\\
\hline
next\_ptr  &	 2\\
varbind.oid\_ptr & 2\\
varbind.value\_type & 1\\
varbind.value & 4\\
\hline
Total & 9\\ 
\hline
\end{tabular}
\caption{Memory estimation for a variable binding.}
\label{tab:listitem}
\end{center}
\end{table}

The overall memory utilized to store an SNMPv1 message with \texttt{N} variable bindings can be found by the following formula: \texttt{13+N(9+4) = 13(N+1)}. The SNMP message size is limited in the implementation to 484 bytes. Each variable binding encoded in the BER format requires at least 7 bytes, therefore, in the worst unrealistic case an SNMPv1 message may carry \texttt{484/7 = 69} variable bindings, which would require \texttt{13(69+1)=910} bytes of the heap size to store such a message.

\subsection{Managed Objects}			
As discussed in Section \ref{sec:mib-ds}, each managed object is stored in memory as an instance of the \texttt{mib\_object\_t} structure. Table \ref{tab:mibobj} presents a memory estimation for the members of this structure.

\begin{table}[ht]
\begin{center}
\begin{tabular}{|l|r|}
\hline
Member &  Size (bytes)\\
\hline
attrs &	 1\\
get\_fnc\_ptr & 2\\
set\_fnc\_ptr & 2\\
get\_next\_oid\_fnc\_ptr & 2\\
next\_ptr & 2\\
varbind.oid\_ptr & 2\\
varbind.value\_type & 1\\
varbind.value & 4\\
\hline
Total & 16\\ 
\hline
\end{tabular}
\caption{Memory estimation for an instance of the \texttt{mib\_object\_t} structure.}
\label{tab:mibobj}
\end{center}
\end{table}
A managed  object uses additional \texttt{4+L} bytes for the OID, where \texttt{L} is the length in bytes of the OID encoded in the BER format. In case a managed object is of a string-based type, \texttt{S} extra bytes are required to store its  value, where \texttt{S} is the length of the value. The total RAM usage for a managed object can be found by the following formula: \texttt{16+(4+L)+S}. Using flash ROM to store OIDs allows to save \texttt{4+L} bytes of RAM for every managed object. In this case, the formula changes to \texttt{16+S}, which would require 1600 bytes of RAM for 100 managed objects of an integer-based type.


\section{Response Latency}\label{sec:latency}
A simple \texttt{upd-echo} application has been developed for Contiki, which allows to get a round-trip time  estimation for a UDP datagram of a certain size. Table \ref{tab:udp-echo} provides some experimental results obtained using \texttt{udp-echo}. The results reveal that the transmission time of an 802.15.4 frame depends significantly on the amount of data being sent. For example, the difference between the round-trip time for datagrams with the payload of 1 byte and 90 bytes, both of which fit into one 802.15.3 frame, is around 8 ms. The delay is caused by the low speed of the radio transceiver. While sending a 91 byte payload the 6LoWPAN fragmentation is used and, as expected, we observe an abrupt increase in the round-trip time comparing to the 90 byte payload.

\begin{table}[ht]
\begin{center}
\begin{tabular}{|r|c|c|c|}
\hline
Payload &  802.15.4& RTT(ms) & Variance\\
(bytes) & frames &  &\\
\hline
1  &	1 & 30.75 &	2.07\\
90 & 	1 &	38.87 &	6.58\\
91 &	2 & 49.90 &	6.54\\
175&	2 & 58.93 &	6.63\\
\hline
\end{tabular}
\caption{Round-trip time (RTT) measured with \texttt{upd-echo}.}
\label{tab:udp-echo}
\end{center}
\end{table}

In order to estimate the SNMP request processing time taken by the agent, the request-response latency for individual messages was measured at the gateway by noting the delay between sending of the message and receiving of the response. In addition to the actual processing time, the measured delay also includes the time to transmit messages over the air between the gateway and the agent. If a message does not fit into a single 802.15.4 frame, the 6LoWPAN fragmentation takes place, which causes additional overhead. The SNMP request processing time can be found as the difference between the the SNMP request-response latency and the round-trip time estimated with \texttt{udp-echo} for datagrams with the same payload length. 

\begin{table}[ht]
\begin{center}
\begin{tabular}{|c|c|l|c|c|c|c|}
\hline
Version & Operation & Security mode& Latency & Variance & RTT & $\Delta$\\
\hline
v1 & Get  & -- & 37.05 & 5.69 & 34.70 & 2.35\\
v1 & Next & -- & 36.98 & 6.58 & 34.70 & 2.28\\
v1 & Set  & -- & 37.14 & 4.39 & 34.70 & 2.44\\
\hline
v3 & Get  & noAuthNoPriv & 56.64 & 4.05 & 52.62 & 4.02\\
v3 & Next & noAuthNoPriv & 56.58 & 2.72 & 52.62 & 3.96\\
v3 & Set  & noAuthNoPriv & 56.78 & 3.00 & 52.62 & 4.16\\
\hline
v3 & Get  & authNoPriv & 91.41 & 3.45 & 53.02 & 38.39\\
v3 & Next & authNoPriv & 91.95 & 3.75 & 53.02 & 38.93\\
v3 & Set  & authNoPriv & 92.41 & 3.22 & 53.02 & 39.39\\
\hline
v3 & Get  & authPriv & 105.70 &	5.38 & 55.03 & 50.67\\
v3 & Next & authPriv & 106.46 & 2.59 & 55.03 & 51.43\\
v3 & Set  & authPriv & 106.73 & 3.59 & 55.03 & 51.70\\
\hline
\end{tabular}
\caption{Experimental results obtained by measuring the response latency (presented in the latency and variance columns) for SNMP requests. The round-trip time (RTT) is estimated using \texttt{upd-echo}.  The last column is the processing time taken by the agent. The measurements are given in milliseconds.}
\label{tab:snmp-latency}
\end{center}
\end{table}

Table \ref{tab:snmp-latency} and Figure \ref{fig:snmp-latency} present latency measurements for SNMPv1 and SNMPv3 in three different security modes. All experiments were done for requests with one variable binding referring to the same MIB object. The first observation is that the time spent in the SNMP request processing is small relative to that spent in data transfer for SNMPv1 and SNMPv3 in the \texttt{noAuthNoPriv} mode. It constitutes only around 6-7\% of the total latency. As expected, the usage of the authentication protocol results in a significant increase of this metric. The results also reveal that  encryption does not have that much impact on the processing time as the authentication does. It is important to mention that the measurements for SNMPv3 do not include the discovery procedure, which would result in an additional message exchange.



\begin{figure}[htp]	
\begin{center}
    \includegraphics[scale = 1.1]{img/latency.pdf}
    \caption{Time taken for transferring and processing an SNMP request.}
	\label{fig:snmp-latency}
\end{center}
\end{figure}
\begin{figure}[htp]	
\begin{center}
    \includegraphics[scale = 1.1]{img/snmpv1-get.pdf}
    \caption{Time spent in transferring and processing SNMPv1 requests and responses as a function of the number of variable bindings in a request.}
	\label{fig:snmp1-get-latency}
\end{center}
\end{figure}

Figure \ref{fig:snmp1-get-latency} shows changes in the processing time by varying the number of variable bindings in a request. These measurements were accomplished for the SNMPv1 protocol and the \texttt{Get} operation. The processing time varies from 2 to 19 ms, which is not significant comparing to the transfer time. Even though the object lookup time depends on its position in the MIB, for this targeted platform it is unlikely that the MIB will contain that many objects to change the results considerably.

\chapter{Conclusions}\label{ch:conclusions}
An implementation of the Simple Network Management Protocol for resource constrained devices under the Contiki Embedded Operating System has been developed. The implementation is modular and extensible by design. It supports the \texttt{Get}, \texttt{GetNext} and \texttt{Set} operations, the SNMPv1 and SNMPv3 message processing models and the User-based Security Model with the HMAC-MD5-96 authentication and CFB128-AES-128 symmetric encryption protocols. The implementation provides an interface to define and configure accessible managed objects. A couple of the existing MIB modules have been implemented for the agent.

The evaluation of the implementation has been carried out on the AVR Raven Board hardware platform. The experimental results reveal that the request processing time for SNMPv1 and SNMPv3 in the \texttt{noAuthNoPriv} mode is relatively small comparing to the transfer time. Using the authentication protocol results in a significant increase of this metric, while the encryption protocol does not have that much impact on it. The RAM and flash
ROM usage has been estimated by using three different approaches.


Possible further work would be to add more features to the implementation. For example, the \texttt{GetBulk} 	operation and the message processing model for SNMPv2c could be implemented. It is also possible to put more effort on defining the Management Information Base for 6LoWPANs.

\appendix
\chapter{Appendix}
\section{Source Code}
The source code and other files necessary to build the project are publicly available for download and experimentation. Access to the source code repository is available using the Apache Subversion control system at \url{http://contiki-snmp.googlecode.com/svn/trunk/}. The project has the following directory structure: 
\begin{itemize}
\item \texttt{app} -- the application which starts the agent's process; 
\item \texttt{src} -- the source code of the agent;
\item \texttt{ber-encoder} -- the source code of the BER encoder utility;
\item \texttt{keygen} -- the source code of the keygen utility;
\item \texttt{test} -- scripts used for testing of the agent;
\item \texttt{contiki} -- Contiki files changed for the agent;
\end{itemize}

\section{Running SNMP Agent}
Use the following steps to install the agent on the AVR Raven board under a Linux computer:
\begin{itemize}
\item Download Contiki 2.4 from \url{http://sourceforge.net/projects/contiki/files/Contiki/Contiki%202.4/contiki-2.4.zip/download}. Unpack the archive to the \texttt{\$SETUP\_ROOT\_DIR} directory:
\begin{mylisting}
\begin{verbatim}
    cd $SETUP_ROOT_DIR
    unzip contiki-2.4.zip
\end{verbatim}
\end{mylisting}

\item Check out the latest source code of the agent from the Subversion repository:
\begin{mylisting}
\begin{verbatim}
    cd $SETUP_ROOT_DIR
    svn checkout http://contiki-snmp.googlecode.com/svn/trunk/ \
                 jacobs-snmp-read-only
\end{verbatim}
\end{mylisting}

\item Modify the file \texttt{\$SETUP\_ROOT\_DIR/jacobs-snmp-read-only/app/Makefile} setting the value of the \texttt{CONTIKI} variable so that it points to the directory \texttt{\$SETUP\_ROOT\_DIR/contiki-2.4}:
\begin{mylisting}
\begin{verbatim}
    6:  CONTIKI=$SETUP_ROOT_DIR/contiki-2.4
\end{verbatim}
\end{mylisting}

\item Create a symbolic link with the name \texttt{snmpd} in the directory \texttt{\$SETUP\_ROOT\_DIR/contiki-2.4/apps} pointing to \texttt{\$SETUP\_ROOT\_DIR/jacobs-snmp-read-only/src}:
\begin{mylisting}
\begin{verbatim}
    cd $SETUP_ROOT_DIR/contiki-2.4/apps
    ln -s ../../jacobs-snmp-read-only/src/ snmpd
\end{verbatim}
\end{mylisting}

\item Update the Contiki files to which changes were applied by running the command:
\begin{mylisting}
\begin{verbatim}
    cp $SETUP_ROOT_DIR/jacobs-snmp-read-only/contiki/* \
       $SETUP_ROOT_DIR/contiki-2.4/cpu/avr/radio/rf230
\end{verbatim}    
\end{mylisting}


\item Compile the agent:
\begin{mylisting}
\begin{verbatim}
    cd $SETUP_ROOT_DIR/jacobs-snmp-read-only/app
    make raven-mib
\end{verbatim}    
\end{mylisting}

\end{itemize}

The command \texttt{make upload} can be used to program the binary on the AVR Raven board.
% Bibliography
\newpage
\bibliographystyle{plain}
\addcontentsline{toc}{chapter}{Bibliography}
\bibliography{msc-thesis}

\nocite{ieee802.15.4}
\nocite{eui64}
\nocite{rfc780}
\nocite{rfc2460}
\nocite{rfc2464}
\nocite{rfc2474}
\nocite{rfc3168}
\nocite{rfc3775}
\nocite{rfc4191}
\nocite{rfc4291}
\nocite{rfc4443}
\nocite{rfc4861}
\nocite{rfc4862}
\nocite{rfc4919}
\nocite{rfc4944}
\nocite{draft-usecases-05}
\nocite{draft-hc-06}
\nocite{draft-nd-07}
\nocite{draft-routing-04}
\nocite{draft-protocols-07}
\nocite{draft-rpl-04}
\nocite{rfc1157}
\nocite{rfc1901}
\nocite{rfc1908}
\nocite{rfc3411}
\nocite{rfc3417}
\nocite{rfc3418}
\nocite{6lowpan-snmp}
\nocite{lnmp}
\nocite{snmp-traf-anal}
\end{document}
